import React from 'react';
import classNames from 'classnames';
import dayjs from 'dayjs';
import _ from 'lodash';

// 导入样式
import './Comment.css';
// 导入图片
import avatar from './avatar.jpg';

export class Comment extends React.Component {
  constructor() {
    super();
    this.state = {
      // hot: 热度排序  time: 时间排序
      tabs: [
        {
          id: 1,
          name: '热度',
          type: 'hot',
        },
        {
          id: 2,
          name: '时间',
          type: 'time',
        },
      ],
      active: 'time',
      list: [
        {
          id: 1,
          author: '刘德华',
          comment: '给我一杯忘情水',
          time: '2021-10-10 09:09:00',
          // 1: 点赞 0：无态度 -1:踩
          attitude: 1,
        },
        {
          id: 2,
          author: '周杰伦',
          comment: '哎哟，不错哦',
          time: '2021-10-11 09:09:00',
          // 1: 点赞 0：无态度 -1:踩
          attitude: 0,
        },
        {
          id: 3,
          author: '五月天',
          comment: '不打扰，是我的温柔',
          time: '2021-10-11 10:09:00',
          // 1: 点赞 0：无态度 -1:踩
          attitude: -1,
        },
      ],
      // 评论内容
      txt: '',
    };
    // 评论输入ref变量
    this.txtRef = React.createRef();
  }

  // 评论输入事件处理函数
  handleTxt = (e) => {
    this.setState({
      txt: e.target.value,
    });
  };

  // 发表评论
  addComment = () => {
    console.log(this.state.txt);
    // 检查输入内容是否为空
    if (!this.state.txt.trim()) return alert('评论内容不能为空');
    // 创建一条评论
    const comment = {
      id: Date.now(),
      author: '韩振',
      comment: this.state.txt,
      time: new Date().toLocaleString(),
      attitude: 1,
    };
    // 修改数组：返回一个新数组
    const newList = [comment, ...this.state.list];
    // 设置页面数据
    this.setState({
      list: newList,
      txt: '',
    });

    // 设置输入框焦点
    this.txtRef.current.focus();
  };

  // 删除评论事件处理
  delComment = (id) => {
    // 从数组中删除一个元素
    console.log(id);
    // const newList = this.state.list.filter((item) => !(item.id === id));
    const newList = this.state.list.filter((item) => item.id !== id);
    // 设置页面数据
    this.setState({
      list: newList,
    });
  };

  // 点赞或点踩事件处理函数
  changeAttitude = (id, attitude) => {
    console.log(id, attitude);
    const newList = this.state.list.map((item) => {
      if (item.id === id) {
        return { ...item, attitude };
      } else {
        return item;
      }
    });
    // 设置页面数据
    this.setState({
      list: newList,
    });
  };

  // 排序
  changeSortType = (type) => {
    console.log(type);
    if (type === 'time') {
      const newList = this.state.list.sort((a, b) => {
        // 日期升序
        // 第1个参数：要排序的数组，第2个参数：要排序的字段，第3个参数：排序方式
        return Date.parse(a.time) - Date.parse(b.time);
        // 日期降序
        // return Date.parse(b.time) - Date.parse(a.time);
      });

      const sorted = _.orderBy(this.state.list, ['time'], ['asc']);
      // 设置页面数据
      this.setState({
        list: sorted,
        active: type,
      });
    } else {
      const newList = this.state.list.sort((a, b) => {
        // id升序
        // return a.id - b.id;
        // id降序
        return b.id - a.id;
      });
      // 设置页面数据
      this.setState({
        list: newList,
        active: type,
      });
    }
  };

  render() {
    return (
      <div className="comment-container">
        {/* 评论数 */}
        <div className="comment-number">
          <span>{this.state.list.length} 评论</span>
        </div>

        {/* 排序tab */}
        <div className="tabs-order">
          {/* 类on选中效果 */}
          {this.state.tabs.map((item) => (
            <div
              className={classNames({ on: this.state.active === item.type })}
              // className={this.state.active === item.type ? 'on' : ''}
              key={item.id}
              onClick={() => this.changeSortType(item.type)}
            >
              按{item.name}排序
            </div>
          ))}
        </div>

        {/* 发表评论区 */}
        <div className="comment-send-container">
          <div>
            <img className="user-head" src={avatar} alt="头像" />
          </div>
          <div className="comment-send">
            <div className="textarea-container">
              <textarea
                cols="80"
                rows="5"
                placeholder="发条友善的评论"
                className="ipt-txt"
                value={this.state.txt}
                onChange={this.handleTxt}
                ref={this.txtRef}
              />
              <button className="comment-submit" onClick={this.addComment}>
                发表评论
              </button>
            </div>
          </div>
        </div>

        {/* 评论列表区 */}
        <div className="comment-list">
          {this.state.list.map((item) => {
            return (
              <div className="comment-item" key={item.id}>
                <div>
                  <img className="user-head" src={avatar} alt="头像" />
                </div>

                <div className="comment">
                  {/* 评论人 */}
                  <div className="user">{item.author}</div>
                  {/* 评论内容 */}
                  <p className="text">{item.comment}</p>
                  <div className="info">
                    <span className="time">
                      {dayjs(item.time).format('YYYY-MM-DD HH:mm:ss')}
                    </span>
                    {/* <span className="like liked"> */}
                    <span
                      className={classNames({
                        like: true,
                        liked: item.attitude === 1,
                      })}
                      // className={item.attitude === 1 ? 'like liked' : 'like'}
                      onClick={() =>
                        this.changeAttitude(
                          item.id,
                          item.attitude === 1 ? 0 : 1
                        )
                      }
                    >
                      <i className="icon" />
                    </span>
                    <span
                      className={classNames({
                        hate: true,
                        hated: item.attitude === -1,
                      })}
                      // className={item.attitude === -1 ? 'hate hated' : 'hate'}
                      onClick={() =>
                        this.changeAttitude(
                          item.id,
                          item.attitude === -1 ? 0 : -1
                        )
                      }
                    >
                      <i className="icon" />
                    </span>
                    <span
                      className="btn-hover"
                      onClick={() => this.delComment(item.id)}
                    >
                      删除
                    </span>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}
